<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>全屏</title>
    <style>
      .box {
        width: 100px;
        height: 100px;
        background: rgb(7, 177, 168);
        cursor: pointer;
      }
      .txt {
        position: relative;
        top: 50%;
        transform: translateY(-50%);
        text-align: center;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <p class="txt">点击全屏</p>
    </div>
    <script>
      // 全屏，默认document，传参element
      function launchFullscreen(element = document.documentElement) {
        if (element.requestFullscreen) {
          element.requestFullscreen();
        } else if (element.mozRequestFullScreen) {
          element.mozRequestFullScreen();
        } else if (element.msRequestFullscreen) {
          element.msRequestFullscreen();
        } else if (element.webkitRequestFullscreen) {
          element.webkitRequestFullScreen();
        }
      }

      //   退出全屏
      function exitFullscreen() {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen();
        }
      }

      //   监听全屏
      document.addEventListener("fullscreenchange", () => {
        document.fullscreenElement
          ? console.info("进入全屏")
          : console.info("退出全屏");
      });

      const boxEle = document.querySelector(".box");
      const boxTxt = document.querySelector(".txt");
      boxEle.addEventListener("click", () => {
        if (document.fullscreenElement) {
          exitFullscreen();
          boxTxt.innerHTML = "点击全屏";
        } else {
          launchFullscreen(boxEle);
          boxTxt.innerHTML = "点击退出全屏";
        }
      });
    </script>
  </body>
</html>
